package com.yf.exam.modules.exam.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.yf.exam.core.api.ApiRest;
import com.yf.exam.core.api.controller.BaseController;
import com.yf.exam.core.api.dto.BaseIdReqDTO;
import com.yf.exam.modules.exam.dto.SelfStudyQuWithRightAnswerDTO;
import com.yf.exam.modules.qu.entity.Qu;
import com.yf.exam.modules.qu.entity.QuAnswer;
import com.yf.exam.modules.qu.entity.QuRepo;
import com.yf.exam.modules.qu.service.QuAnswerService;
import com.yf.exam.modules.qu.service.QuRepoService;
import com.yf.exam.modules.qu.service.QuService;
import com.yf.exam.modules.repo.dto.RepoDTO;
import com.yf.exam.modules.repo.entity.Repo;
import com.yf.exam.modules.repo.service.RepoService;
import com.yf.exam.modules.sys.user.dto.response.SysUserLoginDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 自主练习
 */
@Api(tags = {"自主练习"})
@RestController
@RequestMapping("/exam/api/study/self")
public class SelfStudyController extends BaseController {
    @Autowired
    private RepoService repoService; // 题库服务
    @Autowired
    private QuRepoService quRepoService; // 试题题库关联 服务
    @Autowired
    private QuService quService; // 题目信息服务
    @Autowired
    private QuAnswerService quAnswerService; // 候选答案 服务

    private final LoadingCache<String, List<QuRepo>> quReposCache = Caffeine.newBuilder()
            .maximumSize(Integer.MAX_VALUE)
            .expireAfterWrite(15, TimeUnit.MINUTES)
            .build(id -> {
                final QueryWrapper<QuRepo> qw = new QueryWrapper<>();
                qw.lambda().eq(QuRepo::getRepoId, id);
                return quRepoService.getBaseMapper().selectList(qw);
            });

    private final LoadingCache<String, Qu> quCache = Caffeine.newBuilder()
            .maximumSize(Integer.MAX_VALUE)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .build(id -> quService.getById(id));

    private final LoadingCache<String, List<QuAnswer>> quAnswersCache = Caffeine.newBuilder()
            .maximumSize(Integer.MAX_VALUE)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .build(id -> quAnswerService.listAnswerByRandom(id));

    private static final Random random = new Random();

    // 从指定的题库id中随机抽取一道试题，包含全部选项、携带有正确答案
    @ApiOperation(value = "生成随机的题目")
    @PostMapping("/random")
    @SentinelResource(value = "random")
    public ApiRest<SelfStudyQuWithRightAnswerDTO> random(@RequestBody BaseIdReqDTO reqDTO) {
        Repo repo = repoService.getById(reqDTO.getId());
        if (Objects.isNull(repo)) {
            return super.failure("题库不存在");
        }
        SysUserLoginDTO userLoginDTO = getLoginUser(); // 获取当前用户
        SelfStudyQuWithRightAnswerDTO re = new SelfStudyQuWithRightAnswerDTO();
        RepoDTO dto = new RepoDTO();
        BeanUtils.copyProperties(repo, dto);
        re.setRepo(dto);
        re.setLoginUser(userLoginDTO);
        List<QuRepo> quRepos = quReposCache.get(reqDTO.getId()); // 获取题库下的所有试题
        List<Qu> qus = quRepos.stream()
                .map(quRepo -> quCache.get(quRepo.getQuId()))
                .collect(Collectors.toList());
        final Qu qu = qus.stream().skip(random.nextInt(qus.size())).findFirst().orElse(null);
        if (Objects.isNull(qu)) {
            return super.failure("题库内没有题目");
        }
        re.setQu(qu);
        List<QuAnswer> answers = quAnswersCache.get(qu.getId());
        re.setAnswers(answers);
        return super.success("生成自主练习题目成功", re);
    }
}
